<?php

//chooses a new question to ask
function new_question($previous=false) {
	$questions_asked = count($GLOBALS['answers_history']);
	$next = false;
	if ($previous) {
		//store the results of the question that was just finished
		//date is stored like so: (last question number)|(average # of tries)|(# of times asked)
		$question_history = explode('|', $GLOBALS['answers_history_sum'][$previous-1]);
		$question_history[0] = count($GLOBALS['answers_history']); //is this off by one or anything?
		$question_history[1] = (($question_history[1] * $question_history[2]) + $GLOBALS['answers_history'][$questions_asked]) / ($question_history[2] + 1) ;  // new average = ((old average * times asked) + (new # of tries)) / (times asked + 1)
		$question_history[2]++;
		$GLOBALS['answers_history_sum'][$previous-1] = implode('|', $question_history);
		// parse the data, calculate percents and summary stats
		foreach ($GLOBALS['answers_history_sum'] as $k => $v) {
			$v = explode('|', $v);
			$factors[] = array ( $v[1], $questions_asked - $v[0] ); // array values are [0]: average number of tries and [1] number of questions ago lasted asked
			$average_tries += $factors[$k][0];
			$average_ago += $factors[$k][1];
			}
		$average_tries = $average_tries / $questions_asked;
		$average_ago = $average_ago / $questions_asked;
		//calculate the standard deviations of the two factors
		foreach ($factors as $f) {
			$stdv_tries += pow($f[0] - $average_tries, 2);
			$stdv_ago += pow($f[1] - $average_ago, 2);
			}
		$stdv_tries = sqrt($stdev_tries / $questions_asked);
		if ($stdv_tries == 0) { $stdv_tries ++; } // prevents division by zero errors
		$stdv_ago = sqrt($stdv_ago / $questions_asked);
		//calculate the weighted value of each question by finding the # of standard deviations away for each factor and then summing them (both factors are weighted equally)
		foreach ($factors as $k => $f) {
			$weights[] = (($f[0] - $average_tries) / $stdv_tries) + (($f[1] - $average_ago) / $stdv_ago);
			}
		// sort the questions and pick one (high value means you should ask the question)
		arsort($weights);
		foreach ($weights as $k => $v) { $next = $k; break; }
		}
	else { //first question... just pick a random one
		$next = rand(0, count($weights) - 1);
		}
	return $next;
	}

?>